package com.tom;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * hello netty server
 * 实现客户端发送一个请求，服务器会返回hello netty
 *
 * @author zx
 * @date 2024-10-04 14:29
 */
public class HelloServer {
    public static void main(String[] args) throws InterruptedException {
        // 定义一对线程组 EventLoopGroup 主线程组 用于接收客户端的连接，但是不做任何处理，跟老板一样，不做事起
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 从线程组 老板线程会把任务丢给他，让手下线程组去做任务
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)// 绑定主从线程组
                    .channel(NioServerSocketChannel.class);// 设置nio双向通道
            // 子处理器,用于处理workerGroup 下面写法是内部类
            // serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            //     /**
            //      * 每一个channel 由多个handler共同组成管道pipeline
            //      * @param ch            the {@link NioSocketChannel} which was registered.
            //      * @throws Exception
            //      */
            //
            //     @Override
            //     protected void initChannel(NioSocketChannel ch) throws Exception {
            //         ch.pipeline().addLast(new StringDecoder());
            //     }
            // });
            // 子处理器,用于处理workerGroup 下面写法是的单独抽取出来。
            serverBootstrap.childHandler(new HelloServerInitializer());

            // 启动server，并设置8088端口号，同时启动方式为同步 ChannelFuture
            ChannelFuture channelFuture = serverBootstrap.bind(8088).sync();
            // 用于监听关闭事件，设置为同步
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }
}
